import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib_example/common/event/test_event.dart';
import 'package:flutter_baselib_example/common/util/ui_utils.dart';

///@date:  2021/5/21 14:03
///@author:  lixu
///@description: 演示EventBus的使用
class EventDemo extends StatefulWidget {
  @override
  _EventDemoState createState() => _EventDemoState();
}

class _EventDemoState extends State<EventDemo> {
  String? eventKey;

  @override
  void initState() {
    ///监听事件
    eventKey = eventBus.on<TestEvent>((event) {
      ToastUtils.show('收到的事件：${event.toString()}');
    });
    ToastUtils.show('监听事件');
    super.initState();
  }

  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('测试Event发送和接收'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: [
            UIUtils.getButton('点击发送事件', () async {
              count++;
              eventBus.emit(TestEvent(0, '当前是第$count个事件'));
            }),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    ///取消监听
    eventBus.off(eventKey);
    ToastUtils.show('取消监听事件');
    super.dispose();
  }
}
